package service

import (
	"shopping/dao/mysql"
	"shopping/errno"
	"shopping/model"
	"shopping/utils/pagination"
	"time"
)

var day14ToHours float64 = 336

type OrderService struct {
	orderDao       mysql.OrderDao
	orderedItemDao mysql.OrderItemDao
	productDao     mysql.ProductDao
	cartDao        mysql.CartDao
	cartItemDao    mysql.ItemDao
}

// NewOrderService 实例化
func NewOrderService(
	orderDao mysql.OrderDao,
	orderedItemDao mysql.OrderItemDao,
	productDao mysql.ProductDao,
	cartDao mysql.CartDao,
	cartItemDao mysql.ItemDao) *OrderService {
	return &OrderService{
		orderDao:       orderDao,
		orderedItemDao: orderedItemDao,
		productDao:     productDao,
		cartDao:        cartDao,
		cartItemDao:    cartItemDao}
}

// CompleteOrder 完成订单
func (c *OrderService) CompleteOrder(userId int64) error {
	// 查询购物车
	currentCart, err := c.cartDao.FindOrCreateByUserId(userId)
	if err != nil {
		return err
	}
	// 查询指定用户的购物车
	cartItems, err := c.cartItemDao.GetItems(currentCart.UserId)
	if err != nil {
		return err
	}
	// 购物车为空
	if len(cartItems) == 0 {
		return errno.ErrEptyCartFound
	}
	// 订单项
	orderedItems := make([]model.OrderedItem, 0)
	for _, item := range cartItems {
		orderedItems = append(orderedItems, *model.NewOrderedItem(item.Count, item.ProductID))
	}
	// 创建订单
	err = c.orderDao.Create(model.NewOrder(userId, orderedItems))
	return err
}

// CancelOrder 取消订单
func (c *OrderService) CancelOrder(uid, oid int64) error {
	currentOrder, err := c.orderDao.FindByOrderId(oid)
	if err != nil {
		return err
	}
	if currentOrder.UserId != uid {
		return errno.ErrInvalidOrderId
	}
	if currentOrder.CreateTime.Sub(time.Now()).Hours() > day14ToHours {
		return errno.ErrCancelDurationPassed
	}
	currentOrder.IsCannceled = true
	err = c.orderDao.Update(*currentOrder)
	return err
}

// GetAll 查询所有的订单
func (c *OrderService) GetAll(page *pagination.Pages, uid int64) *pagination.Pages {
	orders, count := c.orderDao.GetAll(page.Page, page.PageSize, uid)
	page.Items = orders
	page.TotalCount = count
	return page
}
